package com.grf.subscribers;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;


/**
 * 发布与订阅：订阅者2
 */
public class Comsumer2 {

    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;//默认的用户名
    private static final String PASSPWRD = ActiveMQConnection.DEFAULT_PASSWORD;//默认的连接密码
    private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL;//默认的连接地址


    public static void main(String[] args) throws JMSException {

        ConnectionFactory connectionFactory;//连接工厂
        Connection connection = null;//连接
        Session session = null;//会话
        Destination destination;//消息目的地
        MessageConsumer messageConsumer = null;//消息生产者


        try {
            //1、连接MQ
            connectionFactory = new ActiveMQConnectionFactory(USERNAME,PASSPWRD,BROKEURL);
            connection =  connectionFactory.createConnection();
            connection.start();
            session = connection.createSession(true,Session.AUTO_ACKNOWLEDGE);
            destination =  session.createTopic("短信发送2");


            messageConsumer = session.createConsumer(destination);
            //2、接收消息
          /*  for (int i = 0; i <5 ; i++) {

                TextMessage text = (TextMessage) messageConsumer.receive();
                System.out.println(text.getText());
            }
*/

          //写MQ的监听器
            messageConsumer.setMessageListener(new MyMessageListener2());


            //session.commit();
            } catch (JMSException e1) {
            e1.printStackTrace();
        }

        }

    static class MyMessageListener2 implements MessageListener {
        @Override
        public void onMessage(Message message) {
            TextMessage textMessage = (TextMessage) message;

            System.out.println("MyMessageListener2--->"+textMessage);

        }
    }
}
